package com.bw.finance.filters;

import com.bw.finance.auth.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginFilter implements GlobalFilter,Ordered{
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("pre:登录过滤");
        String s = exchange.getRequest().getURI().toString();
        if (s.contains("login")){
            return chain.filter(exchange).then(Mono.fromRunnable(()->{
                System.out.println("post:登录响应过滤");
            }));
        }
        if (s.contains("zhuce")||s.contains("sendcode")||s.contains("find")||s.contains("save")||s.contains("msg")){
            return chain.filter(exchange).then(Mono.fromRunnable(()->{
                System.out.println("post:登录响应过滤");
            }));
        }
        MultiValueMap<String, HttpCookie> cookies = exchange.getRequest().getCookies();
        String token="";
        List<HttpCookie> cookie = cookies.get("token");
        for (HttpCookie hc:cookie) {
            if(hc.getName().equals("token")){
                token=hc.getValue();
            }
        }
        UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(token);
        if(userInfo==null){
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        redisTemplate.expire(token,30, TimeUnit.MINUTES);
        /*Cookie cookie = new Cookie("token",token);
        cookie.setMaxAge(1800);
        cookie.setPath("/");
        exchange.getResponse().addCookie(cookie);*/
        return chain.filter(exchange).then(Mono.fromRunnable(()->{
            System.out.println("post:登录响应过滤");
        }));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
